home *** CD-ROM | disk | FTP | other *** search
/ PC-X 1997 October / pcx14_9710.iso / swag / delphi.swg / 0184_Com ports in Delphi 2.0.pas < prev    next >
Encoding:
Pascal/Delphi Source File  |  1996-11-29  |  2.2 KB  |  58 lines

  1.  
  2. >What I need to do is write an arbitrary number of bytes to a serial
  3. >port.  Period.  No modem commands, no acknowledgement from the
  4. >distant end of the serial line, no reading of the port (at least, not
  5. >yet), no nothing except FOR i := 1 TO X DO Send(AByte);
  6.  
  7. Well, that's an easy task in D2.  Here is how you open the port:
  8.  
  9.   Var Port:STRING;  Handle:INTEGER;
  10.  
  11.   Port:='COM2';  // or whatever COM port
  12.   Handle:=CreateFile(PChar(Port),GENERIC_READ+GENERIC_WRITE,
  13.                                0,nil,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0);
  14.   If Handle=INVALID_HANDLE_VALUE then exit; // handle the error if it didn't open
  15.  
  16.   SetupComm(8192,8192);  // works best if you set the buffer size high
  17.  
  18. Now you write the characters to the port using one of two ways...
  19.  
  20. Using WriteFile:
  21.  
  22.   Var DataToSend:STRING;  Written:DWORD;
  23.  
  24.    WriteFile(Handle,DataToSend[1],Length(String),Written,Nil);
  25.  
  26. The above will use the buffer to send the data, so it will return before
  27. the actual data has been sent to the port, so be sure to delay a bit
  28. before closing the port so you don't truncate the outgoing data.  The
  29. parameters are Modem handle, Where the data is, The number of
  30. bytes to send, Returns the number of bytes actually sent, and the last
  31. parameter is if you want to do overlapped writes (sounds to me like
  32. you don't need to in your situation).
  33.  
  34. The other way to send data to the port is
  35.  
  36.   Var K:CHAR;
  37.   While not TransmitCommChar(Handle,K) do Application.ProcessMessages;
  38.  
  39. This sends one character at a time.  TransmitCommChar will return
  40. FALSE if the last character sent hasn't actually gone out the port yet,
  41. so you have to loop like above to send every character. It also returns
  42. FALSE if the port hasn't been opened properly, so make sure it was
  43. opened before you get stuck in a loop somewhere./
  44.  
  45. When you are done with the port, use
  46.  
  47.    CloseHandle(Handle);
  48.  
  49. To close the port and turn off the modem.   Make sure you do this
  50. in your error handlers because if the application terminates without
  51. doing this you'll have to reboot your system to get access to the
  52. COM port a second time.
  53.  
  54. I hope this is what you were looking for.
  55.  
  56. Regards, Keith
  57.  
  58.